package com.rbac.web.db;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.rbac.web.model.Permission;
import com.rbac.web.model.PermissionAction;
import com.rbac.web.model.PermissionType;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

/**
 * @author gengaoliu
 */
@Data
@SuperBuilder
@TableName(value = "permission", autoResultMap = true)
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
public class PermissionDO extends BaseDO {

  private String code;
  private String name;
  private String value;
  private String type;
  private Integer menuId;
  private Integer pId;
  private String remark;
  private String action;
  private Integer sort;
  private String displayName;
  private String icon;
  private String path;

  @TableField(typeHandler = JacksonTypeHandler.class)
  private List<Integer> pIds;

  @TableField(typeHandler = JacksonTypeHandler.class)
  private List<Integer> menuIds;

  public static PermissionDO from(Permission permission) {
    return PermissionDO.builder()
        .id(permission.getId())
        .code(permission.getCode())
        .name(permission.getName())
        .value(permission.getValue())
        .type(permission.getType().getValue())
        .menuId(permission.getMenuId())
        .pId(permission.getPId())
        .remark(permission.getRemark())
        .action(PermissionAction.getActionValue(permission.getAction()))
        .sort(permission.getSort())
        .displayName(permission.getDisplayName())
        .icon(permission.getIcon())
        .path(permission.getPath())
        .createBy(permission.getCreatedBy())
        .createTime(permission.getCreatedTime())
        .updateTime(permission.getUpdatedTime())
        .updateBy(permission.getUpdatedBy())
        .deleted(permission.getDeleted())
        .pIds(permission.getPIds())
        .menuIds(permission.getMenuIds())
        .build();
  }

  public Permission toPermission() {
    return Permission.builder()
        .id(getId())
        .code(code)
        .name(name)
        .value(value)
        .type(PermissionType.getByValue(type))
        .menuId(menuId)
        .pId(pId)
        .remark(remark)
        .action(PermissionAction.getByValue(action))
        .sort(sort)
        .displayName(displayName)
        .icon(icon)
        .path(path)
        .createdBy(this.getCreateBy())
        .createdTime(this.getCreateTime())
        .updatedTime(this.getUpdateTime())
        .updatedBy(this.getUpdateBy())
        .deleted(this.getDeleted())
        .pIds(pIds)
        .menuIds(menuIds)
        .build();
  }
}
